<script setup>
  /**
   * & 文件引入区域
   */
  import { useRouter } from "vue-router";
  import { ToastFun } from "@/hook/toast";
  import { useUseStore } from "@/stores/user";
  import { exchange } from "@/stores/exchange";
  import { reactive, ref, onBeforeMount, watchEffect } from "vue";
  import {
    getTraditionList,
    selectTradinyOrderByUid,
  } from "@/server/api/userInfo";
  import { getJWTFun } from "@/hook/jsrsasign";

  /**
   * & 注册区
   */
  const props = defineProps(["type"]);
  // const props = defineProps(["type", "keyWord"]);
  // exchange().getTraListReq.piName = props.keyWord;
  /**
   * & 变量声明区
   */
  const router = useRouter();
  const loading = ref(false);
  const finished = ref(false);
  const isOne = ref(true)
  let baseUrl = useUseStore().ing; // 图片拼接基础路径
  /**
   * & 函数区
   */
  // 切换交易方式更新列表
  const changeTypeFun = (id) => {
    if (id != exchange().getTraListReq.typeId || exchange().isCuRequire) {
      // 更改id并且清空数据重新重新请求
      exchange().isCuRequire = false
      exchange().getTraListReq.typeId = id;
      exchange().getTraListReq.page = 1;
      exchange().exchangeList = [];
      loading.value = true;
      finished.value = false;
      ToastFun("Loading", { duration: 1000 });
      isOne.value = true
      getTraListFun()
    }
  };

  // 加载分页方法
  const onLoad = () => {
    // 异步更新数据
    setTimeout(async () => {
      if (props.type == "list") {
        getTraListFun();
      } else if (props.type == "order") {
        getTraOrderFun();
      }
    }, 1000);

  };

  // 获取交易列表
  const getTraListFun = async () => {
    let { data } = await getTraditionList(exchange().getTraListReq);
    if (data.code != "200") {
      finished.value = true;
      return;
    }
    exchange().getTraListReq.page += 1;

    exchange().exchangeList.push(...data.data);
    loading.value = false
    if (data.data.length < exchange().getTraListReq.limit) {
      finished.value = true;
    }
    if (isOne.value) {
      isOne.value = false
      ToastFun(t("pay.success2"), {})
    }
  };

  // 获取用户订单
  const getTraOrderFun = async () => {
    let token = getJWTFun({
      userId: useUseStore().userId,
      page: exchange().traOrderPage.page,
      limit: exchange().traOrderPage.limit,
    });

    let { data } = await selectTradinyOrderByUid(token);
    if (data.code != "200") {
      finished.value = true;
      return;
    }
    exchange().traOrderPage.page += 1

    exchange().userOrderList.push(...data.data);
    loading.value = false
    if (data.data.length < exchange().traOrderPage.limit) {
      finished.value = true;
    }
  };

  // 跳转订单详情页
  const toOrderDetail = (id, type, typeId) => {
    // 切换类型到订单页面进行条件渲染
    exchange().orderType = type;
    if (typeId < 2) {
      // 路由跳转
      router.push({
        path: "/exchangeOrder",
        query: {
          id,
        },
      });
    } else if (typeId > 1) {
      router.push({
        path: "/exchangeOrderCurrency",
        query: {
          id,
        },
      });
    }


  };

  // 生命周期
  onBeforeMount(() => {
    if (props.type == "list") {
      exchange().getTraListReq.piName = ""
      exchange().exchangeList = [];
      exchange().getTraListReq.page = 1;
    }

    // 如果数据为空且类型为order，发起首次请求
    if (props.type == "order") {
      loading.value = false
      finished.value = false
      exchange().userOrderList = []
      exchange().traOrderPage.page = 1
    }
  });
  // 将方法暴露给父组件
  defineExpose({ changeTypeFun });
</script>

<template>
  <div class="exchangeOrder" v-if="(exchange().exchangeList && type == 'list') ||
      (exchange().userOrderList && type == 'order')
      ">
    <van-list :finished-text="$t('shop.shopList.finish')" v-model:loading="loading" :finished="finished" @load="onLoad"
      offset="0">
      <div class="items" v-for="(item, i) in type == 'list'
        ? exchange().exchangeList
        : exchange().userOrderList" :key="i">
        <div class="top">
          <div class="user">
            <img :src="item.userImage || '/images/pipayshop_logo.png'" alt="" />
            <div class="name">{{ item.userName }}</div>
          </div>

          <div class="type">
            <!-- ecny和pi币互换 -->
            <div v-if="item.typeId < 2">
              {{
              item.typeId == 0 ? $t("exchange.needECNY") : $t("exchange.needPi")
              }}
            </div>
            <!-- ecny和钱换 -->
            <div v-if="item.typeId > 1">
              {{ item.content }}
            </div>
          </div>
        </div>

        <div :class="['center', item.typeId == 0 ? 'reverse' : '']">
          <div class="item">eCNY {{ item.pointBalance }}</div>

          <div class="img">
            <img src="/images/Me/兑换.png" alt="" />
            <!-- <span>交换</span> -->
          </div>

          <div class="item" v-if="item.typeId < 2">Pi {{ item.piBalance }}</div>
          <!-- typeId的类型是2就是积分换现金 -->
          <div class="item" v-if="item.typeId > 1">Currency {{ item.piBalance }}</div>

        </div>

        <div class="bottom">
          <span></span>

          <!-- 交易按钮，在个人订单页面不渲染 -->
          <div class="btn" @click="toOrderDetail(item.tradinId, 'transaction', item.typeId)"
            v-if="type == 'list' && item.publisherUid != useUseStore().userId">
            {{ $t("exchange.trade") }}
          </div>

          <!-- 个人订单已经在交易状态渲染 item.status == 2 -->
          <div class="btn" @click="toOrderDetail(item.orderId, 'comfirm', item.typeId)" v-if="type == 'order'">
            {{
            item.status == 3
            ? $t("exchange.completed")
            : $t("exchange.trading")
            }}
          </div>
        </div>
      </div>
    </van-list>
  </div>
</template>

<style lang="scss" scoped>
  .exchangeOrder {
    position: relative;

    .items {
      padding: 12rem;
      margin-bottom: 8rem;
      box-shadow: 0rem 5rem 10rem -3rem rgba(143, 143, 143, 0.3);
      border-radius: 16rem;

      >.top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 14rem;

        >.user {
          display: flex;
          align-items: center;

          >img {
            width: 24rem;
            height: 24rem;
            margin-right: 8rem;
          }

          >.name {
            font-size: 14rem;
            font-weight: 400;
            line-height: 20rem;
            color: #666;
          }
        }

        >.type {
          font-size: 16rem;
          font-weight: 400;
          line-height: 22rem;
          color: #333;
        }
      }

      >.center {
        position: relative;

        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10rem;

        &.reverse {
          flex-direction: row-reverse;
        }

        >.item {
          font-size: 20rem;
          font-weight: 500;
          line-height: 28rem;
          color: #333;
        }

        >.img {
          width: max-content;
          position: absolute;
          left: 0;
          right: 0;
          margin: 0 auto;

          font-size: 12rem;

          display: flex;
          align-items: center;

          >img {
            width: 20rem;
            margin-right: 4rem;
          }
        }
      }

      >.bottom {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;

        height: 28rem;

        >span {
          font-size: 14rem;
          font-weight: 400;
          line-height: 20rem;
          color: #333;
        }

        >.btn {
          font-size: 14rem;
          font-weight: 500;
          line-height: 20rem;
          color: #fff;

          width: 110rem;
          height: 28rem;
          text-align: center;

          background: #642e8e;
          padding: 4rem 0rem;

          border-radius: 6rem;

          box-sizing: border-box;
        }
      }
    }
  }
</style>